﻿/*
 * 
 * Author: Martin Paulík
 * 
 */ 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Schema;
using System.IO;

namespace PB138___projekt
{
    /// <summary>
    /// Class and form for import and export from/to Google Drive
    /// </summary>
    public partial class ImportExport : Form
    { 
        
        string code;
        DataManipulator data = new DataManipulator();
        ApplicationAuth app = new ApplicationAuth("54adf9ea166374caea8bdab5e7827b1cf9acd398-privatekey.p12");
        UserAuth user = new UserAuth();
        string path;
        bool val = false;

        /// <summary>
        /// Starts import/export by value and value2.
        /// </summary>
        /// <param name="value">If value == true => import/export by copy code. Otherwise by appliacation.</param>
        /// <param name="value2">If value2 == true => import, otherwise export.</param>
        public ImportExport(bool value, bool value2 = false)
        {
            val = value2;
            if (value == true)
            {
                user.AskForAuthorization();
                InitializeComponent();
                if (value2 == true)
                    this.Text = "Authenticate of import";
                else
                    this.Text = "Authenticate of export";
            }
            else
            {
                path = data.GetContent(app);
                if(value2 == true)
                    xsdAndXsl();

            }

        }
        /// <summary>
        /// Sets and gets value of path
        /// </summary>
        public string Path {get; set;}

        /// <summary>
        /// Calls transformation from videos.xml to content.xml, calls removing DTD declaration on content.xml and 
        /// calls storing data on Google Drive.  
        /// </summary>
        /// <param name="value">If value == true => by coping code, otherwise by application. </param>
        public void export(bool value)
        {
            transformation("VideosToOdsTransform.xsl", "videos.xml", "content.xml");
            removeDtd("content.xml");
            if (value == true)
            {
                data.StoreData(user, "content.xml", "sample.ods");
            }
            else
            {
                data.StoreData(app, "content.xml", "sample.ods");
            }
            data.DeleteTempFiles(true);
        }

        /// <summary>
        /// Calls validating of textBox.
        /// </summary>
        /// <param name="sender">Object</param>
        /// <param name="e">EventArgs</param>
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1_Validating(new object(), new CancelEventArgs()); 
        }
        /// <summary>
        /// Stops showing of errorProvider.
        /// </summary>
        /// <param name="sender">Object</param>
        /// <param name="e">EventArgs</param>
        private void textBox1_Validated(object sender, EventArgs e)
        {
            errorProvider1.SetError(textBox1, "");
        }

        /// <summary>
        /// Check if textBox is valid. If text is empty, it shows errorProvider. Otherwise get autentization and close form. 
        /// If this was open because of import (val == true), then calling transformation from content.xml to videos.xml and 
        /// validating xsd schema. Otherwise calls export. 
        /// </summary>
        /// <param name="sender">Object</param>
        /// <param name="e">CancelEventArgs</param>
        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            if (textBox1.Text.Length == 0)
            {
                e.Cancel = true;
                textBox1.Select(0, textBox1.Text.Length);
                errorProvider1.SetError(textBox1, "The field cannot be empty.");
            }
            else
            {
                getAutentization();
                this.Close();
                if (val == true)
                {
                    xsdAndXsl();
                    
                }
                else
                {
                    export(true);
                }

            }
        }

        /// <summary>
        /// Calls transformation, removing DTD declaration and validating. 
        /// </summary>
        private void xsdAndXsl()
        {
            transformation("OdsToVideosTransfrom.xsl", path, "videos.xml");
            removeDtd("videos.xml");
            validation();
        }
        
        /// <summary>
        /// Gets autentization and path to file. 
        /// </summary>
        private void getAutentization()
        {
            code = textBox1.Text;
            user.CreateAuthenticator(code);
            path = data.GetContent(user);
            
        }

        /// <summary>
        /// Do transformation from input to output by xsl.
        /// </summary>
        /// <param name="xsl">Path to xsl file.</param>
        /// <param name="input">Path to input file.</param>
        /// <param name="output">Path to output file.</param>
        private void transformation(string xsl, string input, string output)
        {
            XslCompiledTransform transf = new XslCompiledTransform();
            transf.Load(xsl);
            transf.Transform(input, output);   
        }

        /// <summary>
        /// Remove DTD declaration from xml file. 
        /// </summary>
        /// <param name="name">Path to file.</param>
        private void removeDtd(string pathFile) //odstrani DTD deklaraci z xml souboru
        {
            XmlReaderSettings set = new XmlReaderSettings();
            set.XmlResolver = null;
            set.DtdProcessing = DtdProcessing.Parse;

            XmlReader str = XmlTextReader.Create(pathFile, set);
            XmlDocument doc = new XmlDocument();
            doc.Load(str);

            if (doc.DocumentType != null)
            {
                XmlDocumentType xdtyp = doc.DocumentType;
                doc.RemoveChild(xdtyp);

            }
            str.Close();
            doc.Save(pathFile);
        }

        /// <summary>
        /// Do validation by videos-schema.xsd. 
        /// </summary>
        private void validation()
        {
            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(null, "videos-schema.xsd");
                settings.ValidationType = ValidationType.Schema;
                XmlDocument document = new XmlDocument();
                document.Load("videos.xml");
                XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
                while (rdr.Read()) { }
            }
            catch
            {
                MessageBox.Show("Validation failed."); 
            }


        }
        /// <summary>
        /// If user click enter in textBox, then calls same function as button_click. 
        /// </summary>
        /// <param name="sender">Object</param>
        /// <param name="e">KeyEventArgs</param>
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                button1_Click(null, null);
        }
    }
}
